package atom.core0.app.thread.pool;
/**
 * Title: 线程池的管理
 * Description:
 * Copyright: Copyright (c) 2010
 * @author hike_man@126.com
 * @version 1.0
 */
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;


//queueSize不能动态修改
//maxPoolSize可以动态修改
public class MutiThreadPool
{
    private static Logger log = Logger.getLogger(MutiThreadPool.class);

    
    private ThreadPoolExecutor taskPool = null; // Thread pool used to hold running threads
    private BlockingQueue taskQueue = null; // Blocking queue used to hold waiting threads

    private int corePoolSize;
    private int maxPoolSize;
    private int queueSize;
    private long waitTime;

    public MutiThreadPool(int iMaxPoolSize) 
    {
        corePoolSize = iMaxPoolSize; // Config in properties, e.g. THREAD_POOL_CORE_SIZE=2
        queueSize = iMaxPoolSize*3; // Config in properties, e.g. THREAD_POOL_QUEUE_SIZE=2
        maxPoolSize = iMaxPoolSize; // Config in properties, e.g. THREAD_POOL_MAX_SIZE=4
        waitTime = 60 ; // Config in properties, e.g. THREAD_KEEP_ALIVE_TIME=60
        taskQueue = new ArrayBlockingQueue(queueSize);
        
        taskPool = new MyThreadPoolExecutor(corePoolSize, maxPoolSize, waitTime,
                TimeUnit.SECONDS, taskQueue, "");
        
        
    }
    public MutiThreadPool(int iMaxPoolSize,String threadDesc) 
    {
        corePoolSize = iMaxPoolSize; // Config in properties, e.g. THREAD_POOL_CORE_SIZE=2
        queueSize = iMaxPoolSize*3; // Config in properties, e.g. THREAD_POOL_QUEUE_SIZE=2
        maxPoolSize = iMaxPoolSize; // Config in properties, e.g. THREAD_POOL_MAX_SIZE=4
        waitTime = 60 ; // Config in properties, e.g. THREAD_KEEP_ALIVE_TIME=60
        taskQueue = new ArrayBlockingQueue(queueSize);
        
        taskPool = new MyThreadPoolExecutor(corePoolSize, maxPoolSize, waitTime,
                TimeUnit.SECONDS, taskQueue, threadDesc);
        
        
    }


    public void execute(Runnable command) 
    {
         taskPool.execute(command); // Some task extends Thread or implements Runnable interface 
    }
    public void setMaximumPoolSize(int iMaxPoolSize)
    {
    	taskPool.setCorePoolSize(iMaxPoolSize);
    	taskPool.setMaximumPoolSize(iMaxPoolSize);
    	
    }
    public boolean ifPoolFull()
    {
    	if (taskPool.getActiveCount() == taskPool.getMaximumPoolSize())
    		return true;
    	else
    		return false;
    }
    public boolean ifWaitingQueueFull()
    {
    	if (taskQueue.size() == queueSize)
    		return true;
    	else
    		return false;
    }    
}

